package com.wang.nowcoder.controller;

import com.wang.nowcoder.pojo.DiscussPost;
import com.wang.nowcoder.pojo.Page;
import com.wang.nowcoder.pojo.User;
import com.wang.nowcoder.service.DiscussPostService;
import com.wang.nowcoder.service.LikeService;
import com.wang.nowcoder.service.UserService;
import com.wang.nowcoder.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wang
 * @ClassName HomeController
 * @Description TODO
 * @date 2021/12/14 15:31
 * @Version 1.0
 */
@Controller
public class HomeController implements CommunityConstant {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    @RequestMapping("/index")
    public String getIndexPage(Model model, Page page){
        page.setRows(discussPostService.selectDiscussPostRows(0));
        page.setPath("/index");
        List<DiscussPost> list = discussPostService.selectDiscussPost(0, page.getOffset(), page.getLimit());
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if (list!=null){
            for (DiscussPost discussPost : list) {
                Map<String,Object> map = new HashMap<>();
                map.put("discussPost",discussPost);
                User user = userService.selectById(discussPost.getUserId());
                map.put("user",user);
                long likeCount = likeService.selectPojoLikeCount(ENTITY_TYPE_POST,discussPost.getId());
                map.put("likeCount",likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        return "index";
    }

    @GetMapping("/error")
    public String getErrorPage() {
        return "/error/500";
    }

}
